package com.ruoyi.web.controller.system;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.OutputCreateChatroom;
import cn.wildfirechat.pojos.OutputGetChatroomInfo;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.ChatroomAdmin;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.TChannel;
import com.ruoyi.system.domain.TChatRoom;
import com.ruoyi.system.domain.TUser;
import com.ruoyi.system.domain.TUserStatus;
import com.ruoyi.system.domain.vo.TChatRoomManagerVo;
import com.ruoyi.system.domain.vo.TChatRoomSearchVo;
import com.ruoyi.system.domain.vo.TChatRoomVo;
import com.ruoyi.system.domain.vo.TUserVo;
import com.ruoyi.system.dto.TChatRoomDTO;
import com.ruoyi.system.dto.TChatRoomManagerDTO;
import com.ruoyi.system.service.ITUserService;
import com.ruoyi.system.service.ITUserStatusService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 聊天室Controller
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@RestController
@RequestMapping("/system/tChatRoom")
@Api("聊天室")
public class TChatRoomController extends BaseController
{
    @Autowired
    private ITUserService tUserService;

    @Autowired
    private ITUserStatusService tUserStatusService;

    /**
     * 查询聊天室
     */
    @ApiOperation(value = "聊天室")
    @GetMapping("/list")
    public TableDataInfo list(TChatRoomSearchVo searchVo)
    {
        startPage();
        List<TChatRoom> list = tUserService.getChatRoomList(searchVo);
        List<TChatRoomDTO> dtos = new ArrayList<>();
        for (TChatRoom tChatRoom : list) {
            TChatRoomDTO tChatRoomDTO = new TChatRoomDTO();
            BeanUtils.copyProperties(tChatRoom,tChatRoomDTO);
            Long dt = tChatRoom.getDt();
            if (dt != null){
                LocalDateTime ldt =
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(dt), ZoneId.systemDefault());
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                tChatRoomDTO.setCreateTime(ldt.format(fmt));
            }
            dtos.add(tChatRoomDTO);
        }
        return getDataTable(dtos);
    }

    /**
     * 获取聊天室详细信息
     */
    @ApiOperation(value = "获取聊天室详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        try {
            IMResult<OutputGetChatroomInfo> chatroomInfo = ChatroomAdmin.getChatroomInfo(id);
            if (chatroomInfo != null && chatroomInfo.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
                TChatRoomDTO tChatRoom = new TChatRoomDTO();
                BeanUtils.copyProperties(chatroomInfo.getResult(), tChatRoom);
                tChatRoom.setCId(chatroomInfo.getResult().getChatroomId());
                return success(tChatRoom);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return error("未找到对应聊天室信息");
    }

    /**
     * 新增/修改聊天室
     */
    @ApiOperation(value = "新增/修改聊天室")
    @Log(title = "聊天室", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TChatRoomVo chatRoomVo) throws Exception {
        IMResult<OutputCreateChatroom> chatroom = ChatroomAdmin.createChatroom(chatRoomVo.getCid(), chatRoomVo.getTitle(), chatRoomVo.getDesc(),
            chatRoomVo.getPortrait(), chatRoomVo.getExtra(), chatRoomVo.getState());
        if (chatroom != null && chatroom.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS && (chatroom.getResult().getChatroomId().equals(chatRoomVo.getCid()) || StringUtils.isEmpty(chatRoomVo.getCid()))) {
            return toAjax(true);
        }
        return toAjax(false);
    }
    /**
     * 新增/删除管理员
     */
    @ApiOperation(value = "新增/删除管理员")
    @Log(title = "新增/删除管理员", businessType = BusinessType.INSERT)
    @PostMapping("/addOrDelManager")
    public AjaxResult addOrDelManager(@RequestBody TChatRoomManagerVo chatRoomManagerVo) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        List<String> uids = chatRoomManagerVo.getUid();
        List<String> failUid = new ArrayList<>();
        if (!uids.isEmpty()){
            // failUid
            List<TUserVo> userList = tUserService.getUserList(chatRoomManagerVo.getUid());
            Map<String, TUserVo> collect = userList.stream().collect(Collectors.toMap(TUserVo::getUid, Function.identity()));
            for (String uid : uids) {
                IMResult<Void> voidIMResult = ChatroomAdmin.setChatroomManager(chatRoomManagerVo.getChatRoomId(), uid,chatRoomManagerVo.getState());
                if (!"success".equals(voidIMResult.getMsg()) ) {
                    TUserVo tUserVo = collect.get(uid);
                    failUid.add(tUserVo.getDisplayName());
                }
            }
        }
        map.put("failUids",failUid);
        return success(map);
    }
    /**
     * 删除聊天室
     */
    @ApiOperation(value = "删除聊天室")
    @Log(title = "聊天室", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) throws Exception {
        for (String id : ids) {
            ChatroomAdmin.destroyChatroom(id);
        }
        return toAjax(true);
    }

    /**
     * 聊天室对应管理员列表
     */
    @ApiOperation(value = "聊天室对应管理员列表")
    @GetMapping("/listByManager/{roomId}")
    public AjaxResult listByManager(@PathVariable String roomId)
    {
        List<TChatRoomManagerDTO> list = tUserService.getListByManager(roomId);
        for (TChatRoomManagerDTO managerDTO : list) {
            Long dt = managerDTO.getDt();
            if (dt != null){
                LocalDateTime ldt =
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(dt), ZoneId.systemDefault());
                managerDTO.setCreateTime(ldt);
            }
        }
        return success(list);
    }

}
